package com.industrial.premu.service.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.databind.util.LRUMap;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.PreMuIndexWeightMain;
import com.industrial.premu.domain.PreMuIndexWeightSub;
import com.industrial.premu.domain.sqsj.PreMuImportAddSubstract;
import com.industrial.premu.mapper.PreMuCompanyInfoMapper;
import com.industrial.premu.mapper.PreMuIndexWeightMainMapper;
import com.industrial.premu.mapper.PreMuIndexWeightSubMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportAddMapper;
import com.industrial.premu.service.IPreMuImportAddSubstractService;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.industrial.premu.mapper.PreMuAddSubstractItemMapper;
import com.industrial.premu.domain.PreMuAddSubstractItem;
import com.industrial.premu.service.IPreMuAddSubstractItemService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 加减分项Service业务层处理
 *
 * @author SangGuangCan
 * @date 2024-01-23
 */
@Service
public class PreMuAddSubstractItemServiceImpl implements IPreMuAddSubstractItemService
{
    @Autowired
    private PreMuAddSubstractItemMapper preMuAddSubstractItemMapper;

    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    @Autowired
    private PreMuIndexWeightMainMapper preMuIndexWeightMainMapper;


    private static final int BATCH_SIZE = 500;

    private static final Pattern pattern = Pattern.compile("^\\d+(\\.\\d+)?$");

    @Autowired
    private IPreMuImportAddSubstractService preMuImportAddSubstractService;

    /**
     * 查询加减分项
     *
     * @param id 加减分项主键
     * @return 加减分项
     */
    @Override
    public AjaxResult selectPreMuAddSubstractItemById(String id)
    {
        PreMuAddSubstractItem preMuAddSubstractItem = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemById(id);
        List<PreMuAddSubstractItem> preMuAddSubstractItems = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemByParentId(id);
        if(preMuAddSubstractItems != null && !preMuAddSubstractItems.isEmpty()){
            preMuAddSubstractItem.setHasLeft(true);
        }else{
            preMuAddSubstractItem.setHasLeft(false);
        }
        return AjaxResult.success(new ArrayList<PreMuAddSubstractItem>(){{add(preMuAddSubstractItem);}});
    }

    /**
     * 查询加减分项列表
     *
     * @param preMuAddSubstractItem 加减分项
     * @return 加减分项
     */
    @Override
    public List<PreMuAddSubstractItem> selectPreMuAddSubstractItemList(PreMuAddSubstractItem preMuAddSubstractItem)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = null;
        if(Objects.isNull(loginUser) || Objects.isNull(sysUser = loginUser.getSysUser())){
            throw new RuntimeException("没有找到当前的登录用户的信息");
        }
        //获取到用户区县的行政区代码
        String district = sysUser.getDistrict();
        preMuAddSubstractItem.setCounty(district);
        preMuAddSubstractItem.setParentId("0");
        return preMuAddSubstractItemMapper.selectPreMuAddSubstractItemList(preMuAddSubstractItem);
    }


    /**
     * 新增加减分项
     *
     * @param preMuAddSubstractItem 加减分项
     * @return 结果
     */
    @Override
    public AjaxResult insertPreMuAddSubstractItem(PreMuAddSubstractItem preMuAddSubstractItem)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if(sysUser == null){
            throw new RuntimeException("没有找到用户信息");
        }

        //前置检查 - 检查子级的分值和会不会大于父级分值
//        if(StringUtils.isNotBlank(preMuAddSubstractItem.getParentId())){
//            PreMuAddSubstractItem parentInfo = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemById(preMuAddSubstractItem.getParentId());
//            BigDecimal itemScore = StringUtils.isNotBlank(parentInfo.getItemScore()) ? new BigDecimal(parentInfo.getItemScore()) : BigDecimal.ZERO;
//            //查询父级下的子级分数和
////            BigDecimal subScoreSum = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemScoreSumByParentId(preMuAddSubstractItem.getParentId());
//            BigDecimal nItemScore = StringUtils.isNotBlank(preMuAddSubstractItem.getItemScore()) ? new BigDecimal(preMuAddSubstractItem.getItemScore()) : BigDecimal.ZERO;
////            subScoreSum = subScoreSum.add(nItemScore);
//            if(itemScore.compareTo(nItemScore) == -1){
//                return AjaxResult.warn("当前子级的分值大于父级的分值，禁止新增");
//            }
//        }
//        else{
//            if(StringUtils.equals(preMuAddSubstractItem.getItemType(),"1")){
//                //检查当前一级的分值和是否会大于指标管理中设置的值
//                PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
//                preMuIndexWeightMain.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
//                preMuIndexWeightMain.setYear(preMuAddSubstractItem.getYear());
//                preMuIndexWeightMain.setCompanyType(preMuAddSubstractItem.getCompanyType());
//                List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectSubList(preMuIndexWeightMain);
//                if(preMuIndexWeightMains != null && !preMuIndexWeightMains.isEmpty()){
//                    PreMuIndexWeightMain temp = preMuIndexWeightMains.get(0);
//                    List<PreMuIndexWeightSub> preMuIndexWeightSubList = temp.getPreMuIndexWeightSubList();
//                    if(preMuIndexWeightSubList != null && !preMuIndexWeightSubList.isEmpty()){
//                        List<PreMuIndexWeightSub> addSubList = preMuIndexWeightSubList.stream().filter(k -> StringUtils.equals(k.getIndexName(), "加减分项")).collect(Collectors.toList());
//                        if(addSubList == null || addSubList.isEmpty()){
//                            return AjaxResult.warn("请先去指标管理中设置加减分项的值");
//                        }
//                        //取出指标管理中的加分项的值
//                        PreMuIndexWeightSub preMuIndexWeightSub = addSubList.get(0);
//                        if(StringUtils.isNotBlank(preMuIndexWeightSub.getIndexValue())){
//                            BigDecimal indexValueBig = new BigDecimal(preMuIndexWeightSub.getIndexValue());
//                            if(indexValueBig.compareTo(BigDecimal.ZERO) == 0){
//                                return AjaxResult.warn("指标管理中的加减分项不可设置为0");
//                            }
//                        }else{
//                            return AjaxResult.warn("请先去指标管理中设置加减分项的值");
//                        }
//
//                        //获取当前区县中父级ID为0的所有加分项
//                        PreMuAddSubstractItem preMuAddSubstractItem1 = new PreMuAddSubstractItem();
//                        preMuAddSubstractItem1.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
//                        preMuAddSubstractItem1.setYear(preMuAddSubstractItem.getYear());
//                        preMuAddSubstractItem1.setCompanyType(preMuAddSubstractItem1.getCompanyType());
//                        preMuAddSubstractItem1.setItemType("1");
//                        preMuAddSubstractItem1.setParentId("0");
//                        List<PreMuAddSubstractItem> preMuAddSubstractItems = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemList(preMuAddSubstractItem1);
//                        if(preMuAddSubstractItems != null && !preMuAddSubstractItems.isEmpty()){
//
//                            BigDecimal indexValueBig = new BigDecimal(preMuIndexWeightSub.getIndexValue());
//
//                            BigDecimal addItemSum = preMuAddSubstractItems.stream()
//                                    .map(k -> StringUtils.isBlank(k.getItemScore()) ? BigDecimal.ZERO : new BigDecimal(k.getItemScore()))
//                                    .reduce(BigDecimal::add)
//                                    .get();
//
//                            //当前要新增的值
//                            BigDecimal fz = StringUtils.isBlank(preMuAddSubstractItem.getItemScore()) ? BigDecimal.ZERO : new BigDecimal(preMuAddSubstractItem.getItemScore());
//                            addItemSum = addItemSum.add(fz);
//                            if(addItemSum.compareTo(indexValueBig) == 1){
//                                return AjaxResult.warn("设置的加分项不可大于指标管理中的加减分项值");
//                            }
//                        }else{
//                            BigDecimal fz = StringUtils.isBlank(preMuAddSubstractItem.getItemScore()) ? BigDecimal.ZERO : new BigDecimal(preMuAddSubstractItem.getItemScore());
//                            BigDecimal indexValueBig = new BigDecimal(preMuIndexWeightSub.getIndexValue());
//                            if(fz.compareTo(indexValueBig) == 1){
//                                return AjaxResult.warn("设置的加分项不可大于指标管理中的加减分项值");
//                            }
//                        }
//                    }else{
//                        return AjaxResult.warn("请先去指标管理中设置加减分项的值");
//                    }
//                }else{
//                    return AjaxResult.warn("请先去指标管理中设置加减分项的值");
//                }
//            }
//        }


        //设置基础信息
        preMuAddSubstractItem.setId(IdUtil.simpleUUID());
        preMuAddSubstractItem.setCreateBy(SecurityUtils.getUserId());
        preMuAddSubstractItem.setCreateDate(DateUtils.getNowDate());
        preMuAddSubstractItem.setDelFlag("0");
        preMuAddSubstractItem.setCounty(sysUser.getDistrict());

        if(StringUtils.isBlank(preMuAddSubstractItem.getParentId())){
            preMuAddSubstractItem.setParentId("0");
        }

        //设置层级
        String newItemLevel = StringUtils.isBlank(preMuAddSubstractItem.getItemLevel()) ? "0" : String.valueOf(Integer.valueOf(preMuAddSubstractItem.getItemLevel()) + 1);
        preMuAddSubstractItem.setItemLevel(newItemLevel);

        //设置层级
        String newItemIndex = StringUtils.isBlank(preMuAddSubstractItem.getItemIndex()) ? "0" : String.valueOf(Integer.valueOf(preMuAddSubstractItem.getItemIndex()) + 1);
        preMuAddSubstractItem.setItemIndex(newItemIndex);



        int i = preMuAddSubstractItemMapper.insertPreMuAddSubstractItem(preMuAddSubstractItem);
        return AjaxResult.success(preMuAddSubstractItem.getId());
    }

    /**
     * 修改加减分项
     *
     * @param preMuAddSubstractItem 加减分项
     * @return 结果
     */
    @Override
    public int updatePreMuAddSubstractItem(PreMuAddSubstractItem preMuAddSubstractItem)
    {

        //前置检查 - 检查子级的分值和会不会大于父级分值
//        if(StringUtils.isNotBlank(preMuAddSubstractItem.getParentId()) && !StringUtils.equals(preMuAddSubstractItem.getParentId(),"0")){
//            PreMuAddSubstractItem parentInfo = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemById(preMuAddSubstractItem.getParentId());
//            BigDecimal itemScore = StringUtils.isNotBlank(parentInfo.getItemScore()) ? new BigDecimal(parentInfo.getItemScore()) : BigDecimal.ZERO;
//
//            //查询出旧的值
////            PreMuAddSubstractItem oldValue = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemById(preMuAddSubstractItem.getId());
////            BigDecimal oldValueBig = StringUtils.isNotBlank(oldValue.getItemScore()) ? new BigDecimal(oldValue.getItemScore()) : BigDecimal.ZERO;
//            //查询父级下的子级分数和
////            BigDecimal subScoreSum = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemScoreSumByParentId(preMuAddSubstractItem.getParentId());
//            BigDecimal nItemScore = StringUtils.isNotBlank(preMuAddSubstractItem.getItemScore()) ? new BigDecimal(preMuAddSubstractItem.getItemScore()) : BigDecimal.ZERO;
////            subScoreSum = subScoreSum.add(nItemScore).subtract(oldValueBig);
//            if(itemScore.compareTo(nItemScore) == -1){
//                throw new RuntimeException("当前子级的分值大于父级的分值，禁止修改");
//            }
//        }

        return preMuAddSubstractItemMapper.updatePreMuAddSubstractItem(preMuAddSubstractItem);
    }

    /**
     * 批量删除加减分项
     *
     * @param ids 需要删除的加减分项主键
     * @return 结果
     */
    @Override
    public int deletePreMuAddSubstractItemByIds(String[] ids)
    {
        return preMuAddSubstractItemMapper.deletePreMuAddSubstractItemByIds(ids);
    }

    /**
     * 删除加减分项信息
     *
     * @param id 加减分项主键
     * @return 结果
     */
    @Override
    public int deletePreMuAddSubstractItemById(String id)
    {
        return preMuAddSubstractItemMapper.deletePreMuAddSubstractItemById(id);
    }

    @Override
    public AjaxResult loadSubNode(String parentId) {
        List<PreMuAddSubstractItem> preMuAddSubstractItems = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemByParentId(parentId);
        for(PreMuAddSubstractItem item : preMuAddSubstractItems){
            String id = item.getId();
            List<PreMuAddSubstractItem> subSbuNodeArgs = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemByParentId(id);
            if(subSbuNodeArgs != null && !subSbuNodeArgs.isEmpty()){
                item.setHasLeft(true);
            }else {
                item.setHasLeft(false);
            }
        }
        return AjaxResult.success(preMuAddSubstractItems);
    }

    @Override
    public AjaxResult getNodeInfoById(String id) {
        PreMuAddSubstractItem preMuAddSubstractItem = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemById(id);
        return AjaxResult.success(preMuAddSubstractItem);
    }


    @Override
    public List<PreMuAddSubstractItem> addSubstractItemList(PreMuAddSubstractItem params) {
        return preMuAddSubstractItemMapper.addSubstractItemList(params);
    }

    /**
     * 查询加减分树表格
     *
     * @param queryParams
     */
    @Override
    public List<PreMuAddSubstractItem> treeList(PreMuAddSubstractItem queryParams) {
        List<PreMuAddSubstractItem> pageList = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemList(queryParams);

        List<PreMuAddSubstractItem> leve1Menu = pageList.stream().filter(AddSubstractItemDO1 ->
                AddSubstractItemDO1.getParentId().equals("0")
        ).map((menu) -> {
            menu.setTreeList(getChildren(menu,pageList));
            return menu;
        }).sorted((menu1, menu2) -> {
            //排序
            int count=( menu1.getItemIndex()==null ? 0 : Integer.valueOf(menu1.getItemIndex()))-(menu2.getItemIndex()==null ? 0 : Integer.valueOf(menu2.getItemIndex()));
            return count;
        }).collect(Collectors.toList());

        return leve1Menu;
    }


    /**
     * 批量删除加减分项
     *
     * @param preMuAddSubstractItems
     * @return
     */
    @Override
    public AjaxResult batchRemoveData(List<PreMuAddSubstractItem> preMuAddSubstractItems) {
        if(preMuAddSubstractItems != null && !preMuAddSubstractItems.isEmpty()){
            List<String> idList = preMuAddSubstractItems.stream().map(PreMuAddSubstractItem::getId).collect(Collectors.toList());
            String[] idArgs = idList.toArray(new String[idList.size()]);
            preMuAddSubstractItemMapper.deletePreMuAddSubstractItemByIds(idArgs);
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.warn("并没有找到您要删除的数据");
    }

    private List<PreMuAddSubstractItem> getChildren(PreMuAddSubstractItem root, List<PreMuAddSubstractItem> all) {
        List<PreMuAddSubstractItem> addItemDOS = all.stream().filter(addItemDO -> {
            return addItemDO.getParentId().equals(root.getId());
        }).map(AddSubstractItemDO -> {
            AddSubstractItemDO.setTreeList(getChildren(AddSubstractItemDO, all));
            return AddSubstractItemDO;
        }).sorted((menu1, menu2) -> {
            int count=(menu1.getItemIndex()==null ? 0 : Integer.valueOf(menu1.getItemIndex()))-(menu2.getItemIndex()==null? 0 : Integer.valueOf(menu2.getItemIndex()));
            return count;
        }).collect(Collectors.toList());
        return addItemDOS;
    }

    /**
     * 导入加减分数据
     * @param year
     * @param companyType
     * @param inputStream
     * @param itemType
     */
    @Override
    public AjaxResult importAddSubstractItemExcelData(String year, String companyType, InputStream inputStream, String itemType) {
        int successNum = 0;
        int updateNum = 0;
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            Workbook wb = WorkbookFactory.create(inputStream);
            if(wb!= null){
                Sheet sheet = wb.getSheetAt(0);
                if(sheet!=null){
                    Row headerRow = sheet.getRow(0);
                    Row headerNameRow = sheet.getRow(1);
                    //全部id
                    List<PreMuAddSubstractItem> asiDOs = new ArrayList<>();
                    int colSum = 0; //列长
                    int rowNum=sheet.getPhysicalNumberOfRows(); //行长
                    PreMuAddSubstractItem queryParams = new PreMuAddSubstractItem();
                    queryParams.setCounty(sysUser.getDistrict());
                    if(headerRow!=null && headerNameRow!=null){
                        queryParams.setCompanyType(companyType);
                        queryParams.setItemType(itemType);
                        List<PreMuAddSubstractItem> colCalssList = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemList(queryParams);
                        colSum = headerRow.getPhysicalNumberOfCells(); //列长
                        //判断是否设置了加减分项
                        if(colCalssList==null || colCalssList.size()<=0){
                            Map<String,String> resultMap = new HashMap<>();
                            resultMap.put("allMsg","模板过期，请重新下载数据模板！");
                            return AjaxResult.error("导入失败",resultMap);
                        }

                        //判断模板是否过期
                        for (int i = 2;i<colSum;i++) {
                            Cell idCell = headerRow.getCell(i);
                            String idSign = idCell.getStringCellValue().replace(" ", "");
                            int sign = 1;
                            for(PreMuAddSubstractItem asiDO:colCalssList) {
                                if (idSign.equals(asiDO.getId())){
                                    asiDO.setItemName(headerNameRow.getCell(i).getStringCellValue());
                                    asiDOs.add(asiDO);
                                    break;
                                }
                                if(sign==colCalssList.size()){
                                    Map<String,String> resultMap = new HashMap<>();
                                    resultMap.put("allMsg","模板过期，请重新下载数据模板！");
                                    return AjaxResult.error("导入失败",resultMap);
                                }
                                sign++;
                            }
                        }
                    }

                    //批处理用
                    Map<String, Object> existMap = new HashMap<String, Object>();
                    List<String> usccList = new ArrayList<String>();
                    List<PreMuImportAddSubstract> existList = new ArrayList<PreMuImportAddSubstract>();
                    List<PreMuImportAddSubstract> addImportList = new ArrayList<PreMuImportAddSubstract>();
                    List<PreMuImportAddSubstract> updateImportList = new ArrayList<PreMuImportAddSubstract>();
                    PreMuCompanyInfo queryParamsTwo = new PreMuCompanyInfo();
                    queryParamsTwo.setCompanyType(companyType);
                    queryParamsTwo.setCounty(sysUser.getDistrict());
                    List<PreMuCompanyInfo> comList = preMuCompanyInfoMapper.selectPreMuCompanyInfoList(queryParamsTwo);
                    if(comList != null && !comList.isEmpty()){
                        comList.forEach(com ->{
                            if(com.getUscc() != null && !"".equals(com.getUscc())) {
                                usccList.add(com.getUscc().trim());
                            }

                        });
                    }
                    PreMuImportAddSubstract preMuImportAddSubstractQuery = new PreMuImportAddSubstract();
                    preMuImportAddSubstractQuery.setYear(year);
                    preMuImportAddSubstractQuery.setCounty(sysUser.getDistrict());
                    preMuImportAddSubstractQuery.setItemType(Long.valueOf(itemType));
                    existList = preMuImportAddSubstractService.getImportExistList(preMuImportAddSubstractQuery);
                    String oldUscc = "";
                    Map<String, Object> itemIdMap = new HashMap<String, Object>();
                    if(existList != null && !existList.isEmpty()) {
                        for(int i= 0; i<existList.size();i++) {
                            PreMuImportAddSubstract item = existList.get(i);
                            if("".equals(oldUscc)){
                                oldUscc = item.getUscc();
                            }
                            if(!oldUscc.equals(item.getUscc())) {
                                existMap.put(oldUscc, itemIdMap);
                                oldUscc = item.getUscc();
                                itemIdMap = new HashMap<String, Object>();
                            }
                            itemIdMap.put(item.getItemId(), item.getId());
                        }
                        existMap.put(oldUscc, itemIdMap);
                    }
                    ExcelUtil<PreMuImportAddSubstract> util = new ExcelUtil<PreMuImportAddSubstract>(PreMuImportAddSubstract.class);
//                    preMuImportAddSubstracts
                    for(int i=2;i<rowNum;i++){
                        headerRow = sheet.getRow(i);
                        if(headerRow != null) {
                            for (int d = 2; d < colSum; d++) {
                                PreMuImportAddSubstract importAddSubstractDO = new PreMuImportAddSubstract();
                                importAddSubstractDO.setItemType(Long.valueOf(itemType));
                                importAddSubstractDO.setYear(year);
                                importAddSubstractDO.setCompanyType(companyType);

                                Cell uscc = headerRow.getCell(0);
                                Cell companyName = headerRow.getCell(1);
                                Cell idCell = headerRow.getCell(d);

                                Object cellValue = util.getCellValue(headerRow, d);

                                BigDecimal cellNumValue = new BigDecimal(0);
                                if(cellValue != null ){
                                    if(cellValue instanceof Double){
                                        cellNumValue = new BigDecimal((Double) cellValue);
                                    }else if(pattern.matcher(cellValue.toString().trim()).matches()){
                                        if(cellValue instanceof BigDecimal){
                                            cellNumValue = cellValue == null ? BigDecimal.ZERO : (BigDecimal) cellValue;
                                        }else if(cellValue instanceof String){
                                            cellNumValue = cellValue == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(cellValue));
                                        }

                                    }
                                }

                                if (idCell != null && cellValue!= null && cellNumValue.doubleValue()!= 0 && companyName != null && uscc != null) {
                                    importAddSubstractDO.setUscc(uscc.getStringCellValue().replace(" ", ""));
                                    importAddSubstractDO.setCompanyName(companyName.getStringCellValue());
                                    importAddSubstractDO.setItemId(asiDOs.get(d - 2).getId());
                                    importAddSubstractDO.setCounty(asiDOs.get(d - 2).getCounty());
                                    importAddSubstractDO.setItemNames(asiDOs.get(d - 2).getItemName());

                                    importAddSubstractDO.setItemScore(cellNumValue);

                                    if (usccList.contains(importAddSubstractDO.getUscc())) {
                                        Map<String, Object> idMap = (Map<String, Object>) existMap.get(importAddSubstractDO.getUscc());
                                        if (idMap != null && idMap.containsKey(importAddSubstractDO.getItemId())) {
                                            importAddSubstractDO.setId((String) idMap.get(importAddSubstractDO.getItemId()));
                                            updateImportList.add(importAddSubstractDO);
                                        } else {
                                            importAddSubstractDO.setId(IdUtil.simpleUUID());
                                            importAddSubstractDO.setCreateDate(DateUtils.getNowDate());
                                            importAddSubstractDO.setCreateBy(SecurityUtils.getUserId());
                                            importAddSubstractDO.setDelFlag("0");
                                            addImportList.add(importAddSubstractDO);
                                        }
                                    }
                                }
                                if (addImportList != null && addImportList.size() >= BATCH_SIZE) {

                                    int importNum = preMuImportAddSubstractService.batchSave(addImportList);
                                    successNum += importNum;
                                    addImportList.clear();
                                    System.gc();
                                }
                                if (updateImportList != null && updateImportList.size() >= BATCH_SIZE) {

                                    int importNum = preMuImportAddSubstractService.batchUpdate(updateImportList);
                                    successNum += importNum;
                                    updateNum += importNum;
                                    updateImportList.clear();
                                    System.gc();
                                }
                            }
                        }
                    }
                    if (addImportList != null && !addImportList.isEmpty()) {

                        int importNum = preMuImportAddSubstractService.batchSave(addImportList);
                        successNum += importNum;
                        addImportList.clear();
                        System.gc();
                    }
                    if (updateImportList != null && !updateImportList.isEmpty()) {

                        int importNum = preMuImportAddSubstractService.batchUpdate(updateImportList);
                        successNum += importNum;
                        updateNum += importNum;
                        updateImportList.clear();
                        System.gc();
                    }
                }
            }
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("msg","恭喜您，共"+successNum+"条数据导入成功！");
            resultMap.put("allMsg","恭喜您，共"+successNum+"条数据导入成功！");
            resultMap.put("sum",String.valueOf(successNum));
            resultMap.put("updateNum",String.valueOf(updateNum));
            resultMap.put("failureNum","0");
            return AjaxResult.success(resultMap);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("数据异常！，请检查您填写的数据");
        }
    }

    @Override
    public Workbook createTemplateWb(PreMuAddSubstractItem paramns) {
        paramns.setParentId("0");

        LocalDate localDate = LocalDate.now();
        paramns.setYear(String.valueOf(localDate.getYear()-1));
        List<PreMuAddSubstractItem> colCalssList = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemList(paramns);


        Workbook wb = new SXSSFWorkbook(500);
        XSSFCellStyle headerStyle = (XSSFCellStyle) wb.createCellStyle();
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);//設置水平垂直
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);//設置垂直居中
        headerStyle.setWrapText(true); //换行
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);    //设置填充方案
        headerStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(180,198,231)));  //设置填充颜色
        SXSSFSheet sheet = ((SXSSFWorkbook) wb).createSheet("加分项减分项");
        sheet.createFreezePane( 0, 2, 0, 2 );//要冻结的列数  要冻结的行数  右边区域[可见]的首列序号 下边区域[可见]的首行序号
        CellRangeAddress cra =new CellRangeAddress(0, 1, 0, 0); // 起始行, 终止行, 起始列, 终止列
        sheet.addMergedRegion(cra);
        CellRangeAddress cra2 =new CellRangeAddress(0, 1, 1, 1); // 起始行, 终止行, 起始列, 终止列
        sheet.addMergedRegion(cra2);
        sheet.setColumnWidth(0,500*11); //設置第一列寬度
        sheet.setColumnWidth(1,500*19);//設置第二列寬度
        SXSSFRow row = sheet.createRow(0);
        row.setZeroHeight(true); //因此本行
        SXSSFCell usccNameCell = row.createCell(0, CellType.STRING);
        usccNameCell.setCellStyle(headerStyle);

        usccNameCell.setCellValue("统一社会信用代码");

        SXSSFCell companyNameCell = row.createCell(1, CellType.STRING);

        companyNameCell.setCellStyle(headerStyle);
        companyNameCell.setCellValue("企业全称");

        SXSSFRow nameRow = sheet.createRow(1);
        SXSSFCell companyNameCell1 = nameRow.createCell(1, CellType.STRING);
        companyNameCell1.setCellStyle(headerStyle);
        int colSign = 2;
        for( PreMuAddSubstractItem addSubstractItemDO:colCalssList){
            paramns.setParentId(addSubstractItemDO.getId());
            List<PreMuAddSubstractItem> colTermList = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemList(paramns);
            if(colTermList!=null && colTermList.size()>0){
                for(PreMuAddSubstractItem colTerm:colTermList) {
                    paramns.setParentId(colTerm.getId());
                    List<PreMuAddSubstractItem> columnList = preMuAddSubstractItemMapper.selectPreMuAddSubstractItemList(paramns);
                    if(columnList!=null && columnList.size()>0){
                        for(PreMuAddSubstractItem column:columnList){
                            sheet.setColumnWidth(colSign,500*25);
                            SXSSFCell indicatorNameCell = nameRow.createCell(colSign, CellType.STRING);
                            SXSSFCell indicatorIdCell = row.createCell(colSign, CellType.STRING);
                            if(column.getItemScore() != null){
                                indicatorNameCell.setCellValue(addSubstractItemDO.getItemName()+"-"+colTerm.getItemName()+"-"+column.getItemName()+ "(" + column.getItemScore() + ")");
                            }else{
                                indicatorNameCell.setCellValue(addSubstractItemDO.getItemName()+"-"+colTerm.getItemName()+"-"+column.getItemName());
                            }
                            indicatorIdCell.setCellValue(column.getId());
                            indicatorIdCell.setCellStyle(headerStyle);
                            indicatorNameCell.setCellStyle(headerStyle);
                            colSign++;
                        }
                    }else {
                        sheet.setColumnWidth(colSign,500*20);
                        SXSSFCell indicatorNameCell = nameRow.createCell(colSign, CellType.STRING);
                        SXSSFCell indicatorIdCell = row.createCell(colSign, CellType.STRING);
                        if(colTerm.getItemScore() != null){
                            indicatorNameCell.setCellValue(addSubstractItemDO.getItemName()+"-"+colTerm.getItemName()+ "(" + colTerm.getItemScore() + ")");
                        }else{
                            indicatorNameCell.setCellValue(addSubstractItemDO.getItemName()+"-"+colTerm.getItemName());
                        }
                        indicatorIdCell.setCellValue(colTerm.getId());
                        indicatorIdCell.setCellStyle(headerStyle);
                        indicatorNameCell.setCellStyle(headerStyle);
                        colSign++;
                    }
                }
            }else{
                sheet.setColumnWidth(colSign,500*12);
                SXSSFCell indicatorNameCell = nameRow.createCell(colSign, CellType.STRING);
                SXSSFCell indicatorIdCell = row.createCell(colSign, CellType.STRING);
                if(addSubstractItemDO.getItemScore() != null){
                    indicatorNameCell.setCellValue(addSubstractItemDO.getItemName()+ "(" + addSubstractItemDO.getItemScore() + ")");
                }else{
                    indicatorNameCell.setCellValue(addSubstractItemDO.getItemName());
                }

                indicatorIdCell.setCellValue(addSubstractItemDO.getId());
                indicatorIdCell.setCellStyle(headerStyle);
                indicatorNameCell.setCellStyle(headerStyle);
                colSign++;
            }
        }

        PreMuCompanyInfo queryParams = new PreMuCompanyInfo();
        queryParams.setCounty(paramns.getCounty());
        queryParams.setCompanyType(paramns.getCompanyType());
        queryParams.setDelFlag("0");
        queryParams.setYear(paramns.getYear());
        List<PreMuCompanyInfo> comList = preMuCompanyInfoMapper.selectPreMuCompanyInfoList(queryParams);
        for(int i=0;i<comList.size();i++) {
            PreMuCompanyInfo companyInfoDO = comList.get(i);
            SXSSFRow comRow = sheet.createRow(i + 2);
            SXSSFCell usccCell = comRow.createCell(0, CellType.STRING);
            SXSSFCell comNameCell = comRow.createCell(1, CellType.STRING);
            usccCell.setCellValue(companyInfoDO.getUscc());
            comNameCell.setCellValue(companyInfoDO.getCompanyName());
        }
        return wb;
    }

    /**
     * 删除加减分项
     *
     * @param preMuAddSubstractItem
     */
    @Override
    public void removeDataByYearAndCompanyType(PreMuAddSubstractItem preMuAddSubstractItem) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if(sysUser == null){
            throw new RuntimeException("没有找到企业信息");
        }
        String district = sysUser.getDistrict();
        if(StringUtils.isBlank(district)){
            throw new RuntimeException("没有找到当前账号的区县编码");
        }
        preMuAddSubstractItem.setCounty(district);
        //通过条件删除加减分项
        preMuAddSubstractItemMapper.deletePreMuAddSubstractItemInfoByTj(preMuAddSubstractItem);
    }
}
